#include <iostream>
#include <pthread.h>
#include <unistd.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int ticket = 5000;
void* BuyTicket(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(ticket > 0)
        {
            std::cout << name  << "Buy:" << ticket << std::endl;
            usleep(100);
            ticket--;
        }
        else
        {
            std::cout << name << "票已售空" << std::endl;
            pthread_cond_wait(&cond, &mutex);
        }
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main()
{
    pthread_t t1, t2 ,t3;

    pthread_create(&t1, nullptr, BuyTicket, (void*)"thread-1"); 
    pthread_create(&t2, nullptr, BuyTicket, (void*)"thread-2");
    pthread_create(&t3, nullptr, BuyTicket, (void*)"thread-3");
    sleep(5);
    while(true)
    {
        sleep(6);
        pthread_mutex_lock(&mutex);
        ticket += 1000;
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond);
    }
    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);

    return 0;
}